//
//  WelcomeViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/12.
//

import Foundation
import LeanCloud
import SwiftUI
class WelcomeViewModel : BaseViewModel {
    @Published var configStatus : Int = 0 // 0为初始化，1成功，2是失败
    @Published var userStatus : Int = 0 // 0为初始化，1成功，2是失败

    //获取网络数据
    func getData() {
        request(isLoading: false) {
            let query = LCQuery(className: "Config")
            let config = try await retry(maxRetries: 5, retryDelayMillis: 300) {
                try await LeancloudManager.instance.getFirst(query: query, modeType: ConfigBean.self)
            }
            try await self.getAiDescribeData(config: config)
            return config
        } suc: { config in
            configManager.config = config
            self.configStatus = 1
        } fail: {_ in
            self.configStatus = 2
        }
    }
    
    //Ai人设
    func getAiDescribeData(config : ConfigBean?) async throws  {
        if let config = config {
            let query = LCQuery(className: "AiDescribe2")
            let config = try await retry(maxRetries: 5, retryDelayMillis: 300) {
                let serveRequest = config.serverRequest ?? ServerRequestBean()
                if (serveRequest.isCloudDescribe()) {
                    showLog("AiDescribe", "请求leanCloud")
                    return try await LeancloudManager.instance.getFirst(query: query, modeType: AiDescribeConfig.self)
                } else {
                    let url = config.serverRequest?.aiDescribe ?? ""
                    showLog("AiDescribe", "请求json文件")
                    return try await CommonNetManager.shared.get(url: url, modeType: AiDescribeConfig.self)
                }
            }
            showLog("AiDescribe","人设请求成功:\(config?.objectId ?? "")")
            await MainActor.run {
                AiDescribeManager.shared.config = config
            }
        }
    }
    
    func getUser() {
        if userManager.isLogin() {
            request(isLoading: false) {
                let query = LCQuery(className: "User_")
                query.whereKey("objectId", .equalTo(userManager.getUserId()))
                let user = try await retry(maxRetries: 5, retryDelayMillis: 300) {
                    return try await LeancloudManager.instance.getFirst(query: query, modeType: UserBean.self)
                }
                if let user = user {
                    if AppStorageManager.shared.deductAiCount != 0 {
                        //如果不为0.则需要更新服务器的信息
                        let count = user.aiChatCount + AppStorageManager.shared.deductAiCount
                        user.aiChatCount = count
                        try await retry(maxRetries: 10, retryDelayMillis: 200) {
                            //保存用户信息
                            //保存成功后，deductAiCount要置空
                            AppStorageManager.shared.deductAiCount = 0
                        }
                    }
                }
                return user
            } suc: { user in
                userManager.user = user
                self.userStatus = 1
            } fail: {_ in
                self.userStatus = 2
            }
        } else {
            self.userStatus = 1
        }
    }
}
